package com.cyzy.service;

import com.cyzy.esbean.ContentsIndex;
import com.cyzy.pojo.TbContents;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LIGHT
 */
@Service
public class ContentsIndexService {
    @Autowired
    private TbContentsService contentsService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public void initIndex() {
        try {
            // 1. 删除已存在的索引
            IndexOperations indexOperations = elasticsearchTemplate.indexOps(ContentsIndex.class);
            if (indexOperations.exists()) {
                indexOperations.delete();
            }

            // 2. 创建新索引
            indexOperations.create();

            // 3. 创建映射
            indexOperations.putMapping(ContentsIndex.class);

            // 4. 同步数据
            List<TbContents> list = contentsService.list();
            System.out.println("从MySQL获取到 " + list.size() + " 条数据");

            if (!list.isEmpty()) {
                List<ContentsIndex> indexList = new ArrayList<>();
                list.forEach(item -> {
                    ContentsIndex contentsIndex = new ContentsIndex();
                    BeanUtils.copyProperties(item, contentsIndex);
                    indexList.add(contentsIndex);
                });

                // 批量保存到ES
                elasticsearchTemplate.save(indexList);
                System.out.println("成功同步 " + indexList.size() + " 条数据到ES");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("初始化ES索引失败: " + e.getMessage());
        }
    }
}